# -*- encoding: utf-8 -*-
import re, os, urlparse
from piston.handler import BaseHandler
from piston.utils import rc, throttle

from idit.dit.models import Dit, Category
from idit import settings

from idit.api.utils import login_required
from django.core.exceptions import ObjectDoesNotExist

import urllib2

class CategoryHandler(BaseHandler):
    allowed_methods = ('GET', 'POST', 'DELETE', 'PUT')
    def create(self, req):
        category = Category(title=req.POST.get('title'), description=req.POST.get('description'))
        category.save()
        return rc.CREATED

class URLHandler(BaseHandler):
    allowed_methods = ('POST')
    def create(self, req):
        url = req.POST.get('url')
        if not url:
            return rc.BAD_REQUEST
        if not urlparse.urlparse(url).scheme:
            url = 'http://'+url 
        res = {'title':os.path.basename(url)}
        try:
            urlres = urllib2.urlopen(url)
            urlheads = urlres.headers
            if urlheads.maintype == 'image':
                res['imgs'] = [url]
            else:
                if urlheads.type == 'text/html':
                    html = re.sub(r'\s+', ' ', urlres.read())
                    try : 
                        html = unicode(html)
                    except(Exception):
                        html = unicode(html,'gbk')
                    title_search = re.search(r'\<title\>(?P<title>.*)\</title\>', html, re.I | re.M)
                    if title_search:
                        res['title'] = title_search.groupdict().get('title')
                    img_search = re.findall(r'([\/\.\w\:\#\-]+\.(jpg|png|bmp))', html, re.I | re.M)
                    if img_search:
                        res['imgs'] = list(set([ urlparse.urljoin(url,img[0]) for img in img_search]))
        except(Exception):
            return rc.BAD_REQUEST
        return res

class DitHandler(BaseHandler):
    allowed_methods = ('GET', 'POST', 'DELETE')

    def read(self, req, id=0):
        try:
            dit = Dit.objects.get(id=id)
            return {'dit':dit}
        except ObjectDoesNotExist:
            return rc.NOT_FOUND

    @throttle(10, 1 * 60) # allow 10 times in 1 minutes
    def create(self, req):
        dit = Dit(user=req.user, category=Category.objects.get(id=req.POST.get('category')), text=req.POST.get('text'), url=req.POST.get('url'), cover=req.POST.get('cover'))
        dit.save()
        return rc.CREATED

    @login_required()
    def delete(self, req, id):
        try:
            dit = Dit.objects.get(id=id)
            if not req.user == dit.user:
                return rc.FORBIDDEN # returns HTTP 401
            dit.delete()
            return rc.DELETED # returns HTTP 204
        except ObjectDoesNotExist:
            return rc.NOT_FOUND

class HomeTimeLineHandler(BaseHandler):
    methods_allowed = ('GET')
    
    @login_required()
    def read(self, req):
        if req.GET.get('until_id') :
            until_id = req.GET.get('until_id')
            dits = Dit.objects.exclude(id__lt=until_id)[:settings.PER_PAGE_DIT_COUNT]
        else :
            dits = Dit.objects.all()[:settings.PER_PAGE_DIT_COUNT]
        return { 'dits': dits }
    
